// components/index-page-alert/index.js
let api = require("../../utils/apiRequest.js");
let wxp = require("../../utils/wxp.js");
let common_js = require("../../utils/common.js");

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    imgUrl: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    shareInfo: {
      filePath: ''
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onClose() {
      this.triggerEvent("close", null, null);
    },
    // 保存海报
    onSave() {
      this.onSavePoster(this.data.imgUrl);
    },
    // 保存海报
    /**
     * 
     * @param {*} icon 下载地址 
     * @param {*} filePath 可以保存的path
     */
    onSavePoster(icon) {
      api.wxDownloadFile(icon).then(res => {
        this.setData({
          shareInfo: {
            ...this.data.shareInfo,
            ...{
              filePath: res
            }
          }
        })
        this.saveToAlbum(this.data.shareInfo.filePath);
      }).catch(err => {
        common_js.log(err);
      })
    },
    //保存到相册
    saveToAlbum: function (filePath) {
      //获取权限
      if (wx.saveImageToPhotosAlbum) {
        wxp.getSetting().then(res => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wxp.authorize({
              scope: 'scope.writePhotosAlbum'
            }).then(res => {
              //直接保存
              this.savePageImageToPhotosAlbum(filePath);
            }).catch(res => {
              //拒绝授权,打开设置
              this.openPhotosAlbumSetting(res);
            });
          } else {
            //3.写入相册
            this.savePageImageToPhotosAlbum(filePath);
          }
        }).catch(res => {
          common_js.log(res);
        });
      } else {
        common_js.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
      }
    },

    //提示打开相册权限
    openPhotosAlbumSetting: function (res, filePath) {
      //授权拒绝
      var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
      if (firstAuthDeny) return;
      //提示打开设置
      wxp.showModal({
        content: '亲，我们未获得您的相册授权，即将打开设置',
        showCancel: true
      }).then(res => {
        return wxp.openSetting();
      }).then(res => {
        var isOpenWriteAuth = res.authSetting['scope.writePhotosAlbum'];
        if (isOpenWriteAuth) {
          this.savePageImageToPhotosAlbum(filePath);
        }
      }).catch(err => {
        common_js.log(err);
      });
    },
    //保存图片到相册
    savePageImageToPhotosAlbum: function (filePath) {
      wx.saveImageToPhotosAlbum({
        filePath,
        success: res => {
          common_js.showToast("保存成功！");
        }
      });
    },
  }
})